package cn.juque.jdfsystem.task;

import cn.hutool.core.collection.CollUtil;
import cn.juque.jdfsystem.enums.RegisterExecuteStatusEnum;
import cn.juque.jdfsystem.entity.RegisterInfo;
import cn.juque.jdfsystem.handler.HttpMessageHandler;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author juque
 * @version 1.0.0
 * <ul>
 *     <li>HeartbeatTask</li>
 * </ul>
 * @date 2023-01-12 00:35:22
 **/
@Service("heartbeatTask")
public class HeartbeatTask extends AbstractTask {

    @Resource
    private HttpMessageHandler httpMessageHandler;

    /**
     * 任务逻辑
     *
     * @param args 参数
     */
    @Override
    public void execute(String[] args) {
        List<String>[] result = this.httpMessageHandler.checkHeartbeat();
        this.updateNormalNode(result[0]);
        this.updateErrorNode(result[1]);
    }

    /**
     * 设置随机休眠等待最大时长 单位：秒
     *
     * @return 秒
     */
    @Override
    protected Integer initSleepTimes() {
        return null;
    }

    @Override
    protected String getTaskName() {
        return "HeartbeatTask";
    }

    /**
     * 变更正常的心跳IP
     * @param list list
     */
    private void updateNormalNode(List<String> list) {
        if(CollUtil.isEmpty(list)) {
            return;
        }
        Set<String> set = CollUtil.newHashSet(list);
        Map<String, RegisterInfo> map = this.registerInfoCache.getAllRegister();
        map.values().stream()
                .filter(f->set.contains(f.getIp()))
                .forEach(f->{
                    if(RegisterExecuteStatusEnum.DOWN_LINE.getCode().equals(f.getExecuteStatus())) {
                        f.setExecuteStatus(RegisterExecuteStatusEnum.EXCEPTION.getCode());
                    }
                    if(RegisterExecuteStatusEnum.EXCEPTION.getCode().equals(f.getExecuteStatus())) {
                        f.setExecuteStatus(RegisterExecuteStatusEnum.NORMAL.getCode());
                    }
                });
    }

    /**
     * 变更异常的心跳IP
     * @param list list
     */
    private void updateErrorNode(List<String> list) {
        if(CollUtil.isEmpty(list)) {
            return;
        }
        Set<String> set = CollUtil.newHashSet(list);
        Map<String, RegisterInfo> map = this.registerInfoCache.getAllRegister();
        map.values().stream()
                .filter(f->set.contains(f.getIp()))
                .forEach(f->{
                    if (RegisterExecuteStatusEnum.EXCEPTION.getCode().equals(f.getExecuteStatus())) {
                        f.setExecuteStatus(RegisterExecuteStatusEnum.DOWN_LINE.getCode());
                    }
                    if (RegisterExecuteStatusEnum.NORMAL.getCode().equals(f.getExecuteStatus())) {
                        f.setExecuteStatus(RegisterExecuteStatusEnum.EXCEPTION.getCode());
                    }
                });
    }
}
